import { createRootRoute, Link, Outlet, useLocation } from '@tanstack/react-router'
import { AuthProvider, useAuth } from '@/contexts/AuthContext'

function RootComponent() {
  return (
    <AuthProvider>
      <RootLayout />
    </AuthProvider>
  )
}

function RootLayout() {
  const { isAuthenticated, isLoading } = useAuth()
  const location = useLocation()

  // 如果用户已登录，直接渲染内容（DashboardLayout会处理header）
  if (isAuthenticated) {
    return (
      <>
        <main className="min-h-screen bg-gray-50 dark:bg-gray-900">
          <Outlet />
        </main>
        
      </>
    )
  }

  // 检查是否是登录页面
  const isLoginPage = location.pathname === '/login'

  // 如果是登录页面，不显示导航栏
  if (isLoginPage) {
    return (
      <>
        <main className="min-h-screen bg-gray-50 dark:bg-gray-900">
          <Outlet />
        </main>
        
      </>
    )
  }

  // 其他未登录页面显示简单的导航栏
  return (
    <>
      <nav className="bg-white dark:bg-gray-800 shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center space-x-8">
              <div className="flex-shrink-0">
                <h1 className="text-xl font-bold text-gray-900 dark:text-white">
                  惠办好
                </h1>
              </div>
              <div className="flex space-x-4">
                <Link 
                  to="/" 
                  className="text-gray-500 hover:text-gray-700 dark:text-gray-300 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium transition-colors [&.active]:text-blue-600 [&.active]:font-semibold"
                >
                  首页
                </Link>
                {!isLoading && (
                  <Link 
                    to="/login" 
                    className="text-gray-500 hover:text-gray-700 dark:text-gray-300 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium transition-colors [&.active]:text-blue-600 [&.active]:font-semibold"
                  >
                    登录
                  </Link>
                )}
              </div>
            </div>
            
            {/* 右侧登录按钮 */}
            <div className="flex items-center space-x-4">
              {isLoading ? (
                <div className="w-8 h-8 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
              ) : (
                <Link 
                  to="/login"
                  className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors"
                >
                  登录
                </Link>
              )}
            </div>
          </div>
        </div>
      </nav>
      <main className="min-h-screen bg-gray-50 dark:bg-gray-900">
        <Outlet />
      </main>
      
    </>
  )
}

export const Route = createRootRoute({
  component: RootComponent,
})
